/* C库和系统头文件 */
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

/* 自定义头文件 */
#include <serial.h>
#include <common.h>
#include <gpio.h>

int pipefd[2];
int is_pipe_valid = 0;
int check_pipe_valid = 0;
char pipe_buf[100] = "Fatigue_";
pthread_mutex_t pipe_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t pip_mutex_cond = PTHREAD_COND_INITIALIZER;

void *pip_read_thread(void *arg)
{
    char buffer[100];
    int is_pipe;
    char *msg;
    int pipe_buf_size = strlen(pipe_buf);
    while(1)
    {   
        pthread_mutex_lock(&pipe_mutex);
        if(check_pipe_valid)
        {
            printf_d("[pipe] pthread_cond_wait\n");
            pthread_cond_wait(&pip_mutex_cond, &pipe_mutex);    /* 条件变量等待pipe有效，开始读取数据 */
            printf_d("[pipe] get pthread_cond\n");
            check_pipe_valid = 0;
        }
        is_pipe = is_pipe_valid;   //此变量在主进程的start_task()和stop_task()中共享
        pthread_mutex_unlock(&pipe_mutex);
        
        /* 如果pipe有效，读取数据 */
        if(is_pipe){
            ssize_t bytes = read(pipefd[0], buffer, sizeof(buffer) - 1);
            printf_d("read: %s\n", buffer);
            if(bytes > 0)
            {
                buffer[bytes] = '\0';
                msg = strtok(buffer, "\n");
                buzzer_alert();     //蜂鸣器鸣叫，进行提醒
                while(msg != NULL)
                {
                    
                    strcat(pipe_buf, msg);
                    uart_send(pipe_buf);     //发送到上位机
                    printf("[Forklift： pip_read_thread] pipe_buf=%s\n",pipe_buf);
                    pipe_buf[pipe_buf_size] = '\0';
                    msg = strtok(NULL, "\n");
                }
            }
            else{
                printf_d("pipe read error, return bytes = %d\n", bytes);
            }
        }
        else
        {
            check_pipe_valid = 1;
        }
        usleep(500000);
    }
}
